package com.dhy.commadstate.util;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.Serializable;
import java.util.Map;

public abstract class BaseCommandSetting<Command extends ICommand> extends AndroidBasicSerializable<BaseCommandSetting> {

    public Command init(Command c) {
        if (c == null) return null;
        load(this);
        MyCommand m = new MyCommand(getDataMap().get(c.name()));
        c.setLog(m.log);
        c.setTesting(m.testing);
        return c;
    }

    @Override
    public BaseCommandSetting load() {
        load(this);
        if (getDataMap().isEmpty()) {
            for (Command c : getAllCommands()) {
                getDataMap().put(c.name(), new MyCommand(c.name(), c.getCode(), c.isLog(), c.isTesting()).toString());
            }
            save();
        }
        return this;
    }

    public abstract Command[] getAllCommands();

    public static String getFilePath(String name) {
        return Environment.getExternalStorageDirectory() + File.separator + FOLDER + File.separator + name;
    }

    public BaseCommandSetting(Context context, String fileName) {
        super(context, getFilePath(fileName));
    }

    @IgnoreSerializable
    private static final String FOLDER = "CommadState";

    public abstract Map<String, String> getDataMap();

    public class MyCommand implements Serializable {
        public MyCommand(String commandString) {
            String[] d = commandString.split(split);
            this.name = d[0];
            this.log = d[1].equals("true");
            this.code = Integer.parseInt(d[2]);
            this.testing = d[3].equals("true");
        }

        public MyCommand(String name, int code, boolean log, boolean testing) {
            this.log = log;
            this.code = code;
            this.name = name;
            this.testing = testing;
        }

        public int code;
        public String name;
        public boolean log;
        public boolean testing;
        public static final String split = ":";

        @Override
        public String toString() {
            return name + split + log + split + code + split + testing;
        }
    }
}
